// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    ip: "192.168.1.100",
    port: 8080,
    value_dht11: 10
  },
  // 事件处理函数
  onLoad() {

  },
  bindKeyInputIP:function(e){
    var that = this
    console.log(e.detail.value)
    that.setData({
      ip: e.detail.value
    })
  },
  bindKeyInputPort:function(e){
    var that = this
    console.log(e.detail.value)
    that.setData({
      port: e.detail.value
    })
  },
  startConnect: function(e) {
    var object = {};
    var that = this;

    console.log("start connect");
    const udp = wx.createUDPSocket()
    const locationPort = udp.bind(8088)

    wx.showToast({
      title: '连接成功',
      icon: 'success',
      duration: 2000
    })

    object['ip'] = that.data.ip; 
    object['port'] = that.data.port;
    var json = JSON.stringify(object);//JSON.stringify()

    udp.send({
      address: that.data.ip,
      port: that.data.port,
      message: json
    })

    // receive
    udp.onListening(function(res){
      console.log('监听中...')
      console.log(res)
    })

    udp.onMessage(function(res){
      console.log(res.message)
      let unit8Arr = new Uint8Array(res.message);
      console.log("unit8Arr is", unit8Arr)
      let encodedString = String.fromCharCode.apply(null, unit8Arr),
      decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码

      console.log('str===' + decodedString)
      var obj =JSON.parse(decodedString);

      that.setData({
        value_dht11: obj.value
      })
    })
  }
})
